package com.museum.guide.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.museum.guide.entity.Appointment;
import com.museum.guide.vo.TimeSlotStatistics;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.util.List;

/**
 * 预约Mapper接口
 */
@Mapper
public interface AppointmentMapper extends BaseMapper<Appointment> {

    /**
     * 查询指定日期和时间段的预约人数
     *
     * @param appointmentDate 预约日期
     * @param timeSlotId      时间段ID
     * @return 预约人数
     */
    @Select("SELECT IFNULL(SUM(visitor_count), 0) FROM appointment WHERE appointment_date = #{appointmentDate} AND time_slot_id = #{timeSlotId} AND status != 'CANCELED'")
    int countVisitorsByDateAndTimeSlot(@Param("appointmentDate") LocalDate appointmentDate,
                                       @Param("timeSlotId") Long timeSlotId);

    @Select("select time_slot.id                                                    slot_id,\n" +
            "       if(total_visitors is null, 0, total_visitors)                as total_visitors,\n" +
            "       max_visitors - if(total_visitors is null, 0, total_visitors) as available_visitors\n" +
            "from appointment_time_slot as time_slot\n" +
            "         left join (select time_slot_id, sum(visitor_count) AS total_visitors\n" +
            "                    from appointment\n" +
            "                    where appointment_date = #{dateStr}\n" +
            "                    group by time_slot_id) AS temp on time_slot.id = temp.time_slot_id\n")
    List<TimeSlotStatistics> getTimeSlotStatistics(@Param("dateStr") String dateStr);
}